package com.cpl.presentation;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cpl.common.pojo.Business;
import com.cpl.common.pojo.Customer;
import com.cpl.web.validator.UserLoginValidator;

@Controller
public class UserLoginController {

	@Autowired
	private UserLoginValidator customerLoginValidator;

	@RequestMapping(method = RequestMethod.GET)
	protected String login(@ModelAttribute Customer customer,
			@ModelAttribute Business business, BindingResult result, Model model)
			throws Exception {
		model.addAttribute("customer", customer);
		model.addAttribute("business", business);
		return "welcomePage";
	}

	@RequestMapping(method = RequestMethod.POST, params = "type")
	protected String Login(@ModelAttribute Customer customer,
			@ModelAttribute Business business, BindingResult result,
			Model model, HttpServletRequest request) throws Exception {
		if (StringUtils.equalsIgnoreCase(request.getParameter("type"),
				"CUSTOMER")) {
			customerLoginValidator.validate(customer, result);
		} else {
			customerLoginValidator.validate(business, result);

		}
		model.addAttribute("customer", customer);
		model.addAttribute("business", business);

		return "welcomePage";
	}
}
